package com.wdc.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.wdc.entity.Files;
import com.wdc.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileMapper fileMapper;

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        //获取后缀名

        //先存储到磁盘
        File uploadParentFile = new File(fileUploadPath);
        //存储数据库
        if (!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
        //获取唯一标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;
        String url = "http://loaclhost:9090/file/" + fileUUID;


        File uploadFile = new File(fileUploadPath + fileUUID);

        //获取文件的md5


        //把获取到的文件存入磁盘目录
        file.transferTo(uploadFile);
        //存储到数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        fileMapper.insert(saveFile);
        return url;

    }


    @GetMapping("/{fileUUID}")
    public void downLoad(@PathVariable String fileUUID,HttpServletResponse response) throws IOException {
        File uploadFile = new File(fileUploadPath + fileUUID );
        response.getOutputStream();

    }

}
